import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { Form, Input, Dialog } from "antd-mobile";
import { BottomBtn, CommonMask } from "@components";
import { REQUIRED_RULE, BARCODE_PARSER } from "@common/constants";
import { createAction, callNativeApi } from "@common/utils";
import {
  SAGA_ORDRE_MOVE_LOAD_OPS_FORM,
  SAGA_ORDER_MOVE_FINISH_OPS,
} from "@store/order-move/saga-types";
import { POP_PAGE_STACK, SET_SCAN_DATA } from "@store/global-state/action-types";
import ItemBlk from "./ItemBlk";

const OrderMoveOpsObj = {
  scanItem: null,
};

const Ops = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const opsFormData = useSelector((state) => state.orderMove.opsFormData);
  const [showMask, setShowMask] = useState(false);
  const scandata = useSelector((state) => state.globalState.scandata);

  useEffect(() => {
    dispatch(
      createAction(SAGA_ORDRE_MOVE_LOAD_OPS_FORM, {
        id: searchParams.get("id"),
      })
    );
    return () => {
      OrderMoveOpsObj.scanItem = null;
      dispatch(createAction(SET_SCAN_DATA, null));
    };
  }, []);

  useEffect(() => {
    if (opsFormData) {
      form.setFields([
        { name: "warehouseName", value: opsFormData.warehouseName },
        { name: "fromLocation", value: opsFormData.fromLocationName },
      ]);
    }
  }, [opsFormData]);

  const setField = ({ parseResult, barcode }) => {
    if (typeof scanItem === "string") {
      form.setFields([
        {
          name: OrderMoveOpsObj.scanItem,
          value: parseResult.locationName,
        },
      ]);
    } else {
      OrderMoveOpsObj.scanItem.callback({ parseResult, barcode });
    }
    setShowMask(false);
  };

  useEffect(() => {
    if (scandata && showMask) {
      if (!OrderMoveOpsObj.scanItem) {
        return;
      }
      callNativeApi({
        classFullName: BARCODE_PARSER,
        action: "parse",
        params: {
          orderId: searchParams.get("id"),
          scanType:
            typeof OrderMoveOpsObj.scanItem === "string"
              ? OrderMoveOpsObj.scanItem
              : OrderMoveOpsObj.scanItem.type,
          barcode: scandata,
          bizType: "ORDER_MOVE",
        },
        needNonce: false,
      })
        .then((resp) => {
          setShowMask(false);
          OrderMoveOpsObj.scanItem = null;
          let response = resp.data ? resp.data : resp;
          if (response.result.status !== "SUCCESS") {
            Dialog.alert({ content: response.result.errorMessage });
          } else {
            setField({
              parseResult: response.payload,
              barcode: scandata,
            });
          }
          dispatch(createAction(SET_SCAN_DATA, null));
          return;
        })
        .catch((error) => {
          setShowMask(false);
          OrderMoveOpsObj.scanItem = null;
          console.log(error);
        });
    }
  }, [scandata]);

  const markScanItem = (params) => {
    setShowMask(true);
    OrderMoveOpsObj.scanItem = params;
  };

  const handleFinish = () => {
    let isInvalid = false;
    let items = [];
    for (let i = 0; i < opsFormData.items.length; i++) {
      if (!opsFormData.items[i].isUnique && !opsFormData.items[i].qty) {
        isInvalid = true;
        break;
      } else if (!opsFormData.items[i].isUnique) {
        items.push({
          id: opsFormData.items[i].id,
          qty: Number(opsFormData.items[i].qty),
        });
      }
    }

    if (isInvalid) {
      Dialog.alert({ content: "请输入物料数量!" });
    } else {
      dispatch(
        createAction(SAGA_ORDER_MOVE_FINISH_OPS, {
          orderId: searchParams.get("id"),
          items,
          callback: () => {
            dispatch(createAction(POP_PAGE_STACK, navigate));
          },
        })
      );
    }
  };

  return (
    <>
      <div style={{ marginTop: "45px", marginBottom: "65px" }}>
        <Form form={form} mode="card">
          <Form.Header>基本信息</Form.Header>
          <Form.Item name="warehouseName" label="仓库">
            <Input readOnly />
          </Form.Item>

          <Form.Header>移库信息</Form.Header>
          <Form.Item
            name="fromLocation"
            label="移出库位"
            rules={REQUIRED_RULE}
            extra={<a onClick={() => markScanItem("fromLocation")}>扫码</a>}
          >
            <Input placeholder="扫码获取" readOnly />
          </Form.Item>
        </Form>

        {opsFormData?.items.map((record, idx) => (
          <ItemBlk key={idx} item={record} markScanItem={markScanItem} />
        ))}
      </div>
      <CommonMask showMask={showMask} txt="请扫码" />
      <BottomBtn
        items={[
          {
            btnTxt: "完成",
            color: "primary",
            handler: handleFinish,
          },
        ]}
      />
    </>
  );
};

export default Ops;
